//
//  AppDelegate.m
//  SMTPSender
//
//  Created by Dante Palacios on 18/08/09.
//  Copyright 2009 Dante Palacios. All rights reserved.
//

#import <MailDelivery/MailDelivery.h>
#import <Security/Security.h>
#import <Security/CMSEncoder.h>

#import "AppDelegate.h"

@interface AppDelegate ()
- (NSDictionary *)messageHeaders;
@end

@implementation AppDelegate

@synthesize content = _content;
@synthesize subject = _subject;

- (id)init 
{
	self = [super init];
	if (self != nil) 
	{
		
	}
	return self;
}

- (void)dealloc
{
	[[NSNotificationCenter defaultCenter] removeObserver:self];

	[_content release];
	_content = nil;
	[_subject release];
	_subject = nil;

	[super dealloc];
}

#pragma mark NSApplication delegate

- (void)applicationDidFinishLaunching:(NSNotification *)notification 
{
	[window center];
	[window makeKeyAndOrderFront:self];
}

- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender 
{
	return YES;
}

- (void)applicationWillTerminate:(NSNotification *)notification 
{
	[self release];
}

#pragma mark actions

- (IBAction)send:(id)sender 
{
	NSDictionary *messageHeaders = [self messageHeaders];
	if (!messageHeaders) 
	{
		NSBeep();
		return;
	}
	
	[self performSelectorInBackground:@selector(sendMessageInBackground:) withObject:messageHeaders];
}

#pragma mark helpers

- (void)sendMessageInBackground:(id)args
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSDictionary *messageHeaders = [args retain];
	
	[sendMessageButton setEnabled:NO];
	[progressIndicator startAnimation:self];
	
	NSError *error = nil;
	if (![SMTPMailDelivery deliverMessage:self.content headers:messageHeaders format:kMultipartAlternativeMessageFormat error:&error])
	{
		NSLog(@"%@", error);
	}
	
	[progressIndicator stopAnimation:self];
	[sendMessageButton setEnabled:YES];
	
	[messageHeaders release];
	[pool drain];
}

#pragma mark getters & setters

- (NSDictionary *)messageHeaders 
{
	NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
	NSString *sender = [userDefaults stringForKey:@"MessageSender"];
	NSString *toRecipients = [userDefaults stringForKey:@"ToRecipients"];
	if (!sender.length || !toRecipients.length || !self.subject.length || !self.content.length) 
	{
		return nil;
	}
	
	NSMutableDictionary *messageHeaders = [NSMutableDictionary dictionary];
	[messageHeaders setObject:sender forKey:@"From"];
	[messageHeaders setObject:toRecipients forKey:@"To"];
	[messageHeaders setObject:self.subject forKey:@"Subject"];
	
	return messageHeaders;
}

@end
